package com.e2oto.seller.common.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;


import com.e2oto.seller.common.utils.LogTools;
import com.e2oto.seller.common.utils.RxBus;
import com.e2oto.seller.modules.seller.bean.RxBusBean;
import com.e2oto.seller.R;
import com.gyf.barlibrary.ImmersionBar;

import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Created by ZhangLiQiang on 2017/9/8.
 */

public abstract class BaseActivity extends AppCompatActivity {

    private static List<Activity> activities = new LinkedList<>();
    protected ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activities.add(this);
        beforeView();
        setContentView(getContentView());
        ButterKnife.bind(this);
        afterView(savedInstanceState);
        initRxbus();

    }

    protected abstract void afterView(Bundle savedInstanceState);

    protected abstract int getContentView();

    protected void beforeView() {
        mImmersionBar = ImmersionBar.with(this).statusBarColor(R.color.theme_color).fitsSystemWindows(true);
        mImmersionBar.init();   //所有子类都将继承这些相同的属性
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        if (mImmersionBar != null)
            mImmersionBar.destroy();
        //移除activity,防止内存泄漏
        activities.remove(this);
        RxBus.getIntanceBus().unSubscribe(this);
    }

    /***
     * 退出app
     */
    public void exitApp() {
        for (int i = 0; i < activities.size(); i++) {
            LogTools.e("finish:" + activities.get(i).toString());
            activities.get(i).finish();
        }
    }

    private void initRxbus() {
        Disposable disposable = RxBus.getIntanceBus().doSubscribe(RxBusBean.class, new Consumer<RxBusBean>() {
            @Override
            public void accept(RxBusBean rxBusMessage) throws Exception {
                //根据事件类型进行处理
                onReceiveRxMessage(rxBusMessage);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogTools.e("RxBusError!!!!!!!!!!" + throwable.toString());
            }
        });
        RxBus.getIntanceBus().addSubscription(this, disposable);
    }

    /**
     * 子类看是否需要重写
     *
     * @param anyType
     */
    protected void onReceiveRxMessage(RxBusBean anyType) {

    }
}
